import { computed, ref } from 'vue'
import type { Ref, WritableComputedRef } from 'vue'

export interface UseBillDetailSelectAllMap {
	[key: string]: boolean
}

export const useBillDetailSelectAll = (billList: Ref<{ id: string }[]>, fn?: Function): { selectAll: WritableComputedRef<boolean>, selectMap: Ref<{ [key: string]: boolean }>, clearSelecteds: () => void, isChecked: (id: string) => boolean, checkedToggle: (id: string) => void, allSelectCount: WritableComputedRef<Number>, selectedCount: WritableComputedRef<Number>, getSelectKeys: () => string[], setSelecteds: (_selectMap: UseBillDetailSelectAllMap) => void, refreshSelectList: (list: { id: string }[]) => void } => {
	const selectMap = ref<UseBillDetailSelectAllMap>({})
	const selectAll = computed({
		get () {
			if (billList.value.length === 0) {
				return false
			}
			return billList.value.every(item => selectMap.value[item.id])
		},
		set (val: boolean) {
			billList.value.forEach((item: { id: string }) => {
				selectMap.value[item.id] = val
			})
			if (fn) {
				fn(val)
			}
		}
	})
	const clearSelecteds = () => {
		selectMap.value = {}
	}
	const setSelecteds = (_selectMap: UseBillDetailSelectAllMap) => {
		selectMap.value = _selectMap
	}
	const isChecked = (id: string) => {
		return selectMap.value[id]
	}
	const checkedToggle = (id: string) => {
		selectMap.value[id] = !selectMap.value[id]
	}
	const allSelectCount = computed(() => {
		return billList.value.length
	})
	const selectedCount = computed(() => {
		return Object.values(selectMap.value).filter(item => !!item).length
	})
	const getSelectKeys = () => {
		return Object.keys(selectMap.value).filter(item => selectMap.value[item])
	}
	const refreshSelectList = (list: { id: string }[]) => {
		billList.value = list
		clearSelecteds()
	}
	return {
		selectAll,
		selectMap,
		clearSelecteds,
		setSelecteds,
		isChecked,
		checkedToggle,
		allSelectCount,
		selectedCount,
		getSelectKeys,
		refreshSelectList
	}
}
